﻿using System;
using System.Collections.Generic;
using System.Text;

namespace ttlang.builder
{
    public static class SystemCall
    {
        static string workingpath;
        static Dictionary<string, string> envvar = new Dictionary<string, string>();
        public static void SetWorkingPath(string _workingpath)
        {
            workingpath = _workingpath;
        }
        public static void SetEnvVar(string key, string value)
        {
            envvar[key] = value;
            //System.Environment.SetEnvironmentVariable("DOTNET_CLI_UI_LANGUAGE", "en");
        }
        public static void ClearEnvVar()
        {
            envvar.Clear();
        }
        public static void Call(string cmd,  Action<string> oninfo, Action<string> onerror)
        {
            var os = System.Environment.OSVersion;
            var op = new System.Diagnostics.ProcessStartInfo();
            foreach (var item in envvar)
            {
                op.Environment.Add(item.Key, item.Value);
            }

            if (os.Platform == PlatformID.Win32NT)
            {
                op.FileName = "cmd.exe";
                op.Arguments = "/c " + cmd;
            }
            else
            {
                op.FileName = "bash";
                op.Arguments = "-c '" + cmd + "'";
            }
            op.UseShellExecute = false;
            op.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
            op.CreateNoWindow = true;
            op.RedirectStandardOutput = true;
            op.RedirectStandardError = true;
            op.RedirectStandardInput = true;
            op.WorkingDirectory = workingpath;



            var process = System.Diagnostics.Process.Start(op);
            process.ErrorDataReceived += (s, e) =>
              {
                  onerror(e.Data);
              };
            process.OutputDataReceived += (s, e) =>
            {
                oninfo(e.Data);
            };
            process.BeginErrorReadLine();
            process.BeginOutputReadLine();
            while (true)
            {
                //var dataline = process.StandardOutput.ReadLine();
              
                //var errline = process.StandardError.ReadLine();
                //if (dataline != null) oninfo(dataline);
                //if (errline != null) oninfo(errline);
                if (process.HasExited)
                    break;

                System.Threading.Thread.Sleep(100);
            }
            process.CancelOutputRead();
            process.CancelErrorRead();

        }
    }
}
